package com.bdth.bdthiss.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.bdth.bdthiss.vo.CommonList;
import com.bdth.bdthiss.vo.MessageResult;
import com.bdth.bdthiss.vo.Pagination;
import com.bdth.bdthiss.entity.Param;
import com.bdth.bdthiss.service.ParamService;
import com.bdth.bdthiss.service.UserService;
import com.bdth.bdthiss.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/20.
 */
@Controller
@RequestMapping("/sys")
public class SystemController extends BaseController {
    @Autowired
    private ParamService paramService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "index")
    public String index() {
        return "sys/index";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Param> getPageList(Pagination pagination, @RequestParam(required = false) String title){
        Page<Param> items = paramService.listPages(pagination, title);
        PageVo<Param> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "form")
    public String form(){
        return "sys/form";
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(Param param){
        boolean flag = paramService.save(param);
        if(flag)
            return MessageResult.getSuccess("添加数据成功");
        else
            return MessageResult.getError("400","添加数据失败");
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public MessageResult update(Param param){
        boolean flag = paramService.update(param);
        if(flag)
            return MessageResult.getSuccess("修改数据成功");
        else
            return MessageResult.getError("400","修改数据失败");
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(@RequestParam Integer ids){
        boolean flag = paramService.delete(ids);
        if(flag)
            return MessageResult.getSuccess("数据已删除");
        else
            return MessageResult.getError("400","数据删除失败");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids){
        boolean flag = paramService.remove(ids);
        if(flag)
            return MessageResult.getSuccess("数据已删除");
        else
            return MessageResult.getError("400","数据删除失败");
    }

    @RequestMapping(value = "search")
    public String search(){
        return "sys/search";
    }

    /**
     * 数据库表页
     * @return
     */
    @RequestMapping(value = "datalist")
    public String datalist(){
        return "sys/datalist";
    }


    /**
     * 数据库表结构页
     * @return
     */
    @RequestMapping(value = "dataform")
    public String dataform() {
        return "sys/dataform";
    }

    public ResponseEntity<FileSystemResource> export(File file, String fileName) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

    /**
     * 数据库备份文件下载
     * @return
     */
    @RequestMapping(value = "datadown")
    public ResponseEntity<FileSystemResource> tablebak(String filename){
        File file = new File("D:\\databak\\"+filename);
        return export(file,filename);
    }

    @RequestMapping(value = "databak")
    public String dataBakList(){
        return "sys/databaklist";
    }



    public File writeFile(String filename,String sql){
        FileOutputStream fop = null;
        File file = null;
        try {
            file = new File("D:\\"+filename);
            fop = new FileOutputStream(file);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // get the content in bytes
            byte[] contentInBytes = sql.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    @RequestMapping(value = "databasebackup",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageResult databasebackup(HttpServletResponse response) throws Exception{
        String dbPath = "D:\\phpStudy\\MySQL\\bin\\";
        String filePath="D:\\databak\\";
        String dbName="andaily";
        String ip = "127.0.0.1";
        String fileName = dbName+"_"+System.currentTimeMillis()+ ".sql";
        try {
            if (SystemController.exportDatabaseTool(dbPath,ip, "root", "root", filePath, fileName, dbName)) {
                return MessageResult.getSuccess("数据库成功备份");
            } else {
                return MessageResult.getSuccess("数据库备份失败");
            }
        } catch (InterruptedException e) {
            return MessageResult.getSuccess("数据库备份失败");
        }
    }

    /**
     * Java代码实现MySQL数据库导出
     *
     * @author GaoHuanjie
     * @param hostIP MySQL数据库所在服务器地址IP
     * @param userName 进入数据库所需要的用户名
     * @param password 进入数据库所需要的密码
     * @param savePath 数据库导出文件保存路径
     * @param fileName 数据库导出文件文件名
     * @param databaseName 要导出的数据库名
     * @return 返回true表示导出成功，否则返回false。
     */
    public static boolean exportDatabaseTool(String dbPath, String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if(!savePath.endsWith(File.separator)){
            savePath = savePath + File.separator;
        }

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            Process process = Runtime.getRuntime().exec(dbPath+"mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine())!= null){
                printWriter.println(line);
            }
            printWriter.flush();
            if(process.waitFor() == 0){//0 表示线程正常终止。
                return true;
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @RequestMapping("/groupsParam")
    @ResponseBody
    public CommonList<Param> findList(@RequestParam String groups){
        List<Param> list = paramService.groupsParam(groups);
        return CommonList.success(list);
    }

    @RequestMapping(value = "groupsText")
    @ResponseBody
    public List<Map<String,Object>> groupsText(@RequestParam String groups){
        List<Param> list = paramService.groupsParam(groups);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Param bean : list){
            Map<String, Object> temp = new HashMap<>();
            temp.put("id", bean.getValue());
            temp.put("text", bean.getTitle());
            result.add(temp);
        }
        return result;
    }

    @RequestMapping(value = "modifypwd", method = RequestMethod.GET)
    public String modifyPassword(){
        return "sys/modifypwd";
    }

    @RequestMapping(value = "changePassword", method = RequestMethod.POST)
    @ResponseBody
    public MessageResult changePassword(String userNameId,String password){
        boolean flag = userService.changePwd(userNameId,password);
        if(flag)
            return MessageResult.getSuccess("操作成功");
        else
            return MessageResult.getError("400","操作失败");
    }
}
